package com.ruoyi.system.controller;

import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.exception.base.BaseException;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.system.domain.RxDoudianAuthor;
import com.ruoyi.system.domain.RxDoudianLiveRecords;
import com.ruoyi.system.mapper.RxDoudianAuthorMapper;
import com.ruoyi.system.mapper.RxDoudianLiveRecordsMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.service.IRxDoudianLiveRecordsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Optional;
import java.util.UUID;

/**
 * 抖店主播直播记录Controller
 *
 * @author hjf
 * @date 2025-04-03
 */
@RestController
@RequestMapping("/hmk/liveRecords")
public class RxDoudianLiveRecordsController extends BaseController {
    @Autowired
    private IRxDoudianLiveRecordsService rxDoudianLiveRecordsService;

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private RxDoudianAuthorMapper rxDoudianAuthorMapper;


    @Autowired
    private RxDoudianLiveRecordsMapper rxDoudianLiveRecordsMapper;


    /**
     * 查询抖店主播直播记录列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:list')")
    @GetMapping("/list")
    public TableDataInfo list(RxDoudianLiveRecords rxDoudianLiveRecords) {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        if (currentUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401); // 401 表示未授权
        }
        List<SysRole> roles = currentUser.getRoles();
        boolean zhuBoQuery = roles.stream().anyMatch(role -> role.getRoleId() == 106L || role.getRoleId() == 111L);
        if (zhuBoQuery) {
            rxDoudianLiveRecords.setManageId(Math.toIntExact(currentUser.getUserId()));
        }
        startPage();
        List<RxDoudianLiveRecords> list = rxDoudianLiveRecordsService.selectRxDoudianLiveRecordsList(rxDoudianLiveRecords);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:list')")
    @GetMapping("/status1List")
    public TableDataInfo status1List() {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        if (currentUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401); // 401 表示未授权
        }
        RxDoudianLiveRecords rxDoudianLiveRecords = new RxDoudianLiveRecords();
        rxDoudianLiveRecords.setStatus(1);
        startPage();
        List<RxDoudianLiveRecords> list = rxDoudianLiveRecordsService.selectRxDoudianLiveRecordsList(rxDoudianLiveRecords);
        return getDataTable(list);
    }


    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:list')")
    @GetMapping("/authorListBySum")
    public TableDataInfo authorListBySum() {
        SysUser currentUser = SecurityUtils.getLoginUser().getUser();
        if (currentUser == null) {
            throw new ServiceException("用户未登录或会话已过期", 401); // 401 表示未授权
        }
        List<RxDoudianAuthor> rxDoudianAuthors = rxDoudianAuthorMapper.selectRxDoudianAuthorList(null);
        List<RxDoudianLiveRecords> list = rxDoudianLiveRecordsMapper.selectRxDoudianLiveRecordsListBySum();
        for (RxDoudianAuthor r : rxDoudianAuthors) {
            Optional<RxDoudianLiveRecords> matchedRecord = list.stream()
                    .filter(n -> n.getDoudianAuthorId() == r.getId().intValue())
                    .findFirst();
            if (matchedRecord.isPresent()) {
                RxDoudianLiveRecords record = matchedRecord.get();
                r.setMonthSum(record.getMonthSum());
                r.setDaySum(record.getDaySum());
            } else {
                System.out.println("未找到匹配记录");
            }
        }
        return getDataTable(rxDoudianAuthors);
    }


    /**
     * 导出抖店主播直播记录列表
     */
    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:export')")

    @PostMapping("/export")
    public void export(HttpServletResponse response, RxDoudianLiveRecords rxDoudianLiveRecords) {
        List<RxDoudianLiveRecords> list = rxDoudianLiveRecordsService.selectRxDoudianLiveRecordsList(rxDoudianLiveRecords);
        ExcelUtil<RxDoudianLiveRecords> util = new ExcelUtil<RxDoudianLiveRecords>(RxDoudianLiveRecords.class);
        util.exportExcel(response, list, "抖店主播直播记录数据");
    }

    /**
     * 获取抖店主播直播记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return success(rxDoudianLiveRecordsService.selectRxDoudianLiveRecordsById(id));
    }

    /**
     * 新增抖店主播直播记录
     */
    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:add')")

    @PostMapping
    public AjaxResult add(@RequestBody RxDoudianLiveRecords rxDoudianLiveRecords) {
        rxDoudianLiveRecords.setStatus(1);//直播中
        List<RxDoudianLiveRecords> oldLiveRecords = rxDoudianLiveRecordsService.selectRxDoudianLiveRecordsList(rxDoudianLiveRecords);
        if (null != oldLiveRecords && oldLiveRecords.size() > 0) {
            throw new BaseException("当前直播间已被占用,请刷新页面!");
        }
        RxDoudianLiveRecords rxDoudianLiveRecords1 = new RxDoudianLiveRecords();
        rxDoudianLiveRecords1.setStatus(1);
        rxDoudianLiveRecords1.setManageId(SecurityUtils.getUserId().intValue());
        List<RxDoudianLiveRecords> oldLiveRecords2 = rxDoudianLiveRecordsService.selectRxDoudianLiveRecordsList(rxDoudianLiveRecords1);
        if (null != oldLiveRecords2 && oldLiveRecords2.size() > 0) {
            throw new BaseException("请先退出其它直播间!");
        }
        long time = System.currentTimeMillis() / 1000;
        rxDoudianLiveRecords.setTime(time);
        rxDoudianLiveRecords.setManageId(SecurityUtils.getUserId().intValue());
        rxDoudianLiveRecords.setStartTime(time);
        rxDoudianLiveRecords.setSerial(UUID.randomUUID().toString());
        return toAjax(rxDoudianLiveRecordsService.insertRxDoudianLiveRecords(rxDoudianLiveRecords));
    }

    /**
     * 修改抖店主播直播记录
     */
    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody RxDoudianLiveRecords rxDoudianLiveRecords) {
        rxDoudianLiveRecords.setStatus(1);
        List<RxDoudianLiveRecords> oldLiveRecords = rxDoudianLiveRecordsService.selectRxDoudianLiveRecordsList(rxDoudianLiveRecords);
        if (null != oldLiveRecords && oldLiveRecords.size() > 0) {
            RxDoudianLiveRecords oldLiveRecord = oldLiveRecords.get(0);
            RxDoudianLiveRecords newLiveRecord = new RxDoudianLiveRecords();
            newLiveRecord.setId(oldLiveRecord.getId());
            long time = System.currentTimeMillis() / 1000;
            newLiveRecord.setEndTime(time);
            newLiveRecord.setStatus(2);
            Long durationL = (time - oldLiveRecord.getStartTime()) / 60;
            newLiveRecord.setDuration(durationL.intValue());
            rxDoudianLiveRecordsService.updateRxDoudianLiveRecords(newLiveRecord);
        }
        return toAjax(1);
    }

    /**
     * 删除抖店主播直播记录
     */
    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:remove')")
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(rxDoudianLiveRecordsService.deleteRxDoudianLiveRecordsByIds(ids));
    }


    /**
     * 根据角色id,获取该角色下的全部用户
     *
     * @return
     */
    @PreAuthorize("@ss.hasPermi('hmk:liveRecords:list')")
    @GetMapping(value = "/selectUserByRoleId")
    public AjaxResult selectUserByRoleId() {
        SysUser sysUser = new SysUser();
        sysUser.setRoleId(106L);
        return success(sysUserMapper.selectUserByRoleId(sysUser));
    }
}
